package com.aiatomic.couting;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.models.TemplateEntity;
import com.aiatomic.couting.models.TemplateGroupEntity;
import com.aiatomic.couting.templates.MyTemplatesFragment;
import com.aiatomic.couting.templates.OnlineTemplatesFragment;
import com.aiatomic.couting.templates.TemplateChangeEventDispatcher;
import com.aiatomic.couting.util.SystemUtil;
import com.aiatomic.couting.widgets.LoadingDialog;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;

import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class TemplatesActivity extends FragmentActivity implements OnClickListener {
    public static final String ACTION_FROM_SETTING = "com.aiatomic.couting.ACTION_FROM_SETTING";
    public static final String ACTION_FROM_MAIN = "com.aiatomic.couting.ACTION_FROM_MAIN";
    private SimpleFragmentPagerAdapter pagerAdapter;
    private ViewPager viewPager;

    private TabLayout tabLayout;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TemplateChangeEventDispatcher.getInstance().clean();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_templates);
        pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this);
        viewPager = (ViewPager) findViewById(R.id.vp_templates);
        viewPager.setAdapter(pagerAdapter);
        tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
        this.findViewById(R.id.vp_templates).setVisibility(View.VISIBLE);
        this.findViewById(R.id.noInternetContent).setVisibility(View.GONE);
        init();
        this.findViewById(R.id.txtDone).setOnClickListener(this);
    }

    private void init() {
        TextView txtBack = (TextView) this.findViewById(R.id.txtBack);
        if (super.getIntent().getAction() == ACTION_FROM_SETTING) {
            txtBack.setText(R.string.bottom_setup);
        } else {
            txtBack.setText(R.string.main);
        }
        txtBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TemplatesActivity.this.onBackPressed();
            }
        });
        TextView txtNext = (TextView) this.findViewById(R.id.txtNext);
        txtNext.setVisibility(View.INVISIBLE);

        TextView txtMiddle = (TextView) this.findViewById(R.id.txtMiddle);
        txtMiddle.setText(R.string.bottom_templates);
    }

    @Override
    public void onClick(View v) {
        MyTemplatesFragment local = (MyTemplatesFragment) pagerAdapter.frgs[0];
        OnlineTemplatesFragment online = (OnlineTemplatesFragment) pagerAdapter.frgs[1];
        // 删除本地或下载到本地
        List<TemplateEntity> toDelete = new ArrayList<TemplateEntity>();
        List<TemplateEntity> toDownload = new ArrayList<TemplateEntity>();
        List<TemplateEntity> localTpls = new ArrayList<TemplateEntity>();
        SystemUtil.getAllLocalStoreTemplates(this, localTpls);
		/*// 本地
		for (TemplateEntity localTpl : localTpls) {
			boolean found = false;
			for (int i = 0; i < local.getAdapter().getCount(); i++) {
				TemplateEntity tTemplate = local.getAdapter().getItem(i);
				if (localTpl.equals(tTemplate)) {
					found = true;
					break;
				}
			}
			if (!found) {
				toDelete.add(localTpl);
			}
		}
		localTpls.removeAll(toDelete);*/
        // 在线
        for (int i = 0; i < online.getAdapter().getCount(); i++) {
            TemplateGroupEntity tGroup = online.getAdapter().getItem(i);
            for (TemplateEntity tTemplate : tGroup.getTemplates()) {
                if (tTemplate.isDownload()) {
                    if (!localTpls.contains(tTemplate)) {
                        toDownload.add(tTemplate);
                    }
                } else {
                    toDelete.add(tTemplate);
                }
            }
        }
        //先删除
				localTpls.removeAll(toDelete);
//        for (TemplateEntity tDel : toDelete) {
//            if (localTpls.contains(tDel)) {
//                File cfg = new File(this.getExternalFilesDir(null),
//                        tDel.getGroup_id() + "_" + tDel.getSb_template_id() + ".cfg");
//                if (cfg.exists()) {
//                    cfg.delete();
//                }
//                File store = new File(SystemUtil.GetTemplateStoreDir(this) + tDel.getGroup_id() + "_"
//                        + tDel.getSb_template_id());
//                if (store.exists()) {
//                    SystemUtil.deleteAllFiles(store);
//                    store.delete();
//                }
//            }
//        }
        if (toDownload.size() > 0) {
			localTpls.removeAll(toDownload);
			localTpls.addAll(toDownload);

//			TemplateDownloadTask downloadTask = new TemplateDownloadTask(this, new IDownloadPostCall() {
//				@Override
//				public void postDownload() {
//					Intent intent = new Intent(TemplatesActivity.this, MainActivity.class);
//					intent.setAction(MainActivity.INTENT_AC_REFRESH_TEMPLATE);
//					startActivity(intent);
//					TemplatesActivity.this.finish();
//				}
//			});
//			TemplateEntity[] array = new TemplateEntity[toDownload.size()];
//			downloadTask.execute(toDownload.toArray(array));
//        } else {
//			Intent intent = new Intent(TemplatesActivity.this, MainActivity.class);
//			intent.setAction(MainActivity.INTENT_AC_REFRESH_TEMPLATE);
//			startActivity(intent);
//			TemplatesActivity.this.finish();
        }
		SystemUtil.saveTpl(this, localTpls);
		Intent intent = new Intent(TemplatesActivity.this, MainActivity.class);
		intent.setAction(MainActivity.INTENT_AC_REFRESH_TEMPLATE);
		startActivity(intent);
		TemplatesActivity.this.finish();

    }

    interface IDownloadPostCall {
        void postDownload();
    }

    class TemplateDownloadTask extends AsyncTask<TemplateEntity, Void, Void> {
        private Context context;
        private LoadingDialog dialog;
        private IDownloadPostCall callback;

        public TemplateDownloadTask(Context context, IDownloadPostCall callback) {
            super();
            this.context = context;
            dialog = new LoadingDialog(context);
            dialog.setMessage(context.getString(R.string.loading_msg5));
            this.callback = callback;
        }

        @Override
        protected Void doInBackground(TemplateEntity... params) {

            for (TemplateEntity tlp : params) {
                File store = new File(SystemUtil.GetTemplateStoreDir(context) + tlp.getGroup_id() + "_"
                        + tlp.getSb_template_id());
                if (!store.exists()) {
                    store.mkdirs();
                }
                URLConnection connection;
                ZipInputStream zipIn = null;
                FileOutputStream fileOut = null;
                ZipEntry zipEntry = null;
                int readedBytes = 0;
                try {
                    URL url = new URL(tlp.getRes_url());
                    connection = url.openConnection();
                    zipIn = new ZipInputStream(connection.getInputStream());
                    while ((zipEntry = zipIn.getNextEntry()) != null) {
                        String entryName = zipEntry.getName();
                        if (zipEntry.isDirectory()) {
                            entryName = entryName.substring(0, entryName.length() - 1);
                            File folder = new File(store.getAbsoluteFile() + File.separator + entryName);
                            folder.mkdirs();
                        } else {
                            String fileName = store.getAbsoluteFile() + File.separator + entryName;
                            File file = new File(fileName);
                            /*
                             * if(file.exists()){ file.delete(); }
                             * file.createNewFile();
                             */
                            fileOut = new FileOutputStream(file);
                            Log.i("DEBUG", file.getAbsolutePath());
                            byte[] downLoadBuffer = new byte[1024];
                            while ((readedBytes = zipIn.read(downLoadBuffer)) > 0) {
                                fileOut.write(downLoadBuffer, 0, readedBytes);
                            }
                            fileOut.close();
                        }
                        zipIn.closeEntry();
                    }
                    zipIn.close();
                    File cfg = new File(context.getExternalFilesDir(null),
                            tlp.getGroup_id() + "_" + tlp.getSb_template_id() + ".cfg");
                    FileOutputStream fileCfgOut = new FileOutputStream(cfg);
                    JSONObject json = new JSONObject();
                    json.put("group_id", tlp.getGroup_id());
                    json.put("sb_template_id", tlp.getSb_template_id());
                    json.put("platform", tlp.getPlatform());
                    json.put("pic", tlp.getPic());
                    json.put("is_recommend", tlp.isIs_recommend());
                    json.put("pos", tlp.getPos());
                    json.put("type", tlp.getType());
                    json.put("desc", tlp.getDesc());
                    json.put("version", tlp.getVersion());
                    json.put("name", tlp.getName());
                    json.put("group_name", tlp.getGroup_name());
                    json.put("t_key", tlp.gettKey());
                    json.put("shape", tlp.getShape());
                    fileCfgOut.write(json.toString().getBytes());
                    fileCfgOut.close();
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.show();
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            callback.postDownload();
            dialog.cancel();
        }

    }
}
